import { cloneDeep } from 'lodash-es'
import { nanoid } from 'nanoid'

export const useTemplateStore = defineStore('template', () => {
  // 选中的模板
  const currentTemplate = ref({})
  // 模板列表
  const templateList = ref([])
  const route = useRoute()
  const localKey = computed(() => 'form-design-' + route.name)

  const resetCurrentTemplate = () => {
    currentTemplate.value = {}
  }

  const getTemplateList = () => {
    try {
      templateList.value =
        JSON.parse(localStorage.getItem(localKey.value)) ?? []
    } catch (err) {
      console.error(err)
    }
  }

  const init = () => {
    resetCurrentTemplate()
    getTemplateList()
  }

  watch(() => route.name, init)
  onMounted(getTemplateList)
  onActivated(getTemplateList)
  onUpdated(getTemplateList)

  const handleCreateTemplate = () => {
    resetCurrentTemplate()
    ElMessage.success({ grouping: true, plain: true, message: '已新建' })
  }
  const handleUpdateCurrentTemplate = async item => {
    resetCurrentTemplate()
    await nextTick()
    currentTemplate.value = item
  }
  const handleUpdateCurrentSchema = item => {
    const _templateItem = {
      ...currentTemplate.value,
      value: item,
    }
    handleUpdateCurrentTemplate(_templateItem)
  }
  const handleSelectTemplate = item => {
    currentTemplate.value = item
  }
  const handleSaveTemplateToLocal = async (schema, name = '') => {
    if (!currentTemplate.value?.id && name === '') {
      const res = await ElMessageBox.prompt('Please input name', 'Tips', {
        inputValue: '保存模板-' + nanoid(8),
      })
      const id = nanoid(8)
      const name = res.value
      schema.id = id
      schema.name = name
      const data = {
        id,
        name,
        value: schema,
      }
      templateList.value.push(data)
    } else {
      const id = currentTemplate.value?.id ?? ''
      const _name = name || currentTemplate.value.name
      schema.id = id
      schema.name = _name
      const data = {
        ...currentTemplate.value,
        name: _name,
        value: schema,
      }
      const index = templateList.value.findIndex(
        item => item.id === currentTemplate.value.id,
      )
      templateList.value.splice(index, 1, data)
    }
    localStorage.setItem(localKey.value, JSON.stringify(templateList.value))
    ElMessage.success({ grouping: true, plain: true, message: '保存成功' })
    // 重新获取模板列表
    getTemplateList()

    // 解决新建模板，页面属性编辑不响应
    await nextTick()
    const _data = templateList.value?.find(
      v => v.id === currentTemplate.value?.id,
    )
    const _item = currentTemplate.value?.id
      ? cloneDeep(_data)
      : cloneDeep(templateList.value?.[templateList.value.length - 1])
    handleUpdateCurrentTemplate(_item)
  }

  const handleDeleteTemplate = async id => {
    await ElMessageBox.confirm('Confirm Delete?', 'Warning')
    templateList.value = templateList.value.filter(item => item.id !== id)
    localStorage.setItem(localKey.value, JSON.stringify(templateList.value))
    ElMessage.success({ grouping: true, plain: true, message: '删除成功' })
    // 重新获取模板列表
    init()
  }
  return {
    templateList,
    currentTemplate,
    handleUpdateCurrentTemplate,
    handleUpdateCurrentSchema,
    handleSelectTemplate,
    handleDeleteTemplate,
    handleSaveTemplateToLocal,
    handleCreateTemplate,
  }
})
